// modules
const response = require('../utils/methods/response.js')
const GoodsModule = require('../models/tableModels/goodsModule.js')

// methods
const dayjs = require("dayjs")
const splitParams = require("../utils/methods/splitParams")
const jsonFormat = require("../utils/methods/jsonFormat")

// 商品控制器
const menuController = {
    // 新增商品
    addGoods: async ({ body }, res) => {
        try {
            const insertData = {
                ...body,
                goodsImageList: JSON.stringify(body.goodsImageList),
                listingTime: dayjs(body.listingType === 1 ? new Date() : body.listingTime).format('YYYY-MM-DD HH:mm:ss'),
                goodsLength: Number(body.goodsLength),
                goodsWidth: Number(body. goodsWidth),
                goodsHeight: Number(body.goodsHeight),
                goodsWeight: Number(body.goodsWeight),
                expressFreight: Number(body.expressFreight),
                limitBuyNum: Number(body.limitBuyNum)
            }
            // 判断是否存在商品
            const isHasGoods = (await GoodsModule.knexAllCount())[0]['count(*)']
            // 首次添加
            if (!isHasGoods) {
                insertData.goodsCode = 'GY0000001'
            } else {
                // 非首次添加，获取最后一个商品的商品编码
                const { goodsCode } = (await GoodsModule.selectLastData())[0]
                const [startSign, codeNum] = [goodsCode.substring(0, 2), Number(goodsCode.substring(2))]
                // 设置商品编码
                insertData.goodsCode = `${startSign.padEnd(9 - String(codeNum).length, '0')}${codeNum + 1}`
            }
            // 插入数据
            const insertGoodsResult = await GoodsModule.insert(insertData)
            insertGoodsResult ? response.success(res) : response.fail(res, '插入失败！')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 删除商品
    deleteGoods: async ({ query }, res) => {
        try {
            // 删除商品
            const deleteResult = await GoodsModule.delete({ goodsId: query.goodsId })
            deleteResult ? response.success(res) : response.fail(res, '删除失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 商品列表
    goodsList: async ({ body }, res) => {
        try {
            const { pageParams, otherParams } = splitParams(body)
            // 响应列表数据、数据总条数
            let responseList, total
            // 如果没有指定字段，则查询所有
            if (!otherParams) {
                // 获取表数据总条数
                total = (await GoodsModule.knexAllCount())[0]['count(*)']
                // 分页查询
                responseList = await GoodsModule.knexAllDescLimitSelect(pageParams, 'goodsId')
            } else {
                // 取出参数的个数和参数值
                const { paramsLength, paramsValue } = otherParams
                // 如果参数值有商品名称，模糊匹配查询商品名称
                if (Object.prototype.hasOwnProperty.call(paramsValue, 'goodsName')) {
                    // 如果只有 goodsName 字段，则直接模糊匹配
                    if (paramsLength === 1) {
                        responseList = await GoodsModule.knexLikeSelectLimitDesc('goodsName', paramsValue.goodsName, pageParams, 'goodsId')
                        total = (await GoodsModule.knexLikeSelect('goodsName', paramsValue.goodsName)).length
                    } else {
                        // 如果还有其他字段，则合并查询
                        const newSearchParams = jsonFormat(paramsValue)
                        delete newSearchParams.goodsName
                        responseList = await GoodsModule.knexLikeAndOtherSelectLimitDesc('goodsName', paramsValue.goodsName, newSearchParams, pageParams, 'goodsId')
                        total = (await GoodsModule.knexLikeAndOtherSelect('goodsName', paramsValue.goodsName, newSearchParams)).length
                    }
                } else {
                    // 无商品名称直接查询其他
                    responseList = await GoodsModule.knexSelectFiledRowLimitDesc(paramsValue, pageParams, 'goodsId')
                    total = (await GoodsModule.knexSelectFiledRow(paramsValue)).length
                }
            }
            // 响应数据
            const responseData = {
                total,
                // 处理时间格式
                list: responseList.length ? jsonFormat(responseList).map(item => {
                    item.goodsImageList = JSON.parse(item.goodsImageList)
                    item.listingTime = dayjs(item.listingTime).format('YYYY-MM-DD HH:mm:ss')
                    item.createdTime = dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss')
                    return item
                }) : []
            }
            response.success(res, responseData)
        } catch(err) {
            response.error(res, err)
        }
    },
    // 商品详情
    goodsDetail: async ({ query }, res) => {
        try {
            // 获取商品详情
            const goodsDetailResult = (await GoodsModule.knexSelectFiledRow({ goodsId: query.goodsId }))[0]
            // 响应数据
            const responseData = {
                ...goodsDetailResult,
                goodsImageList: JSON.parse(goodsDetailResult.goodsImageList),
                listingTime: dayjs(goodsDetailResult.listingTime).format('YYYY-MM-DD HH:mm:ss')
            }
            goodsDetailResult ? response.success(res, responseData) : response.fail(res, '获取失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 更新商品状态
    updateGoodsStatus: async ({ body }, res) => {
        try {
            console.log('请求参数', body)
            response.success(res)
        } catch(err) {
            response.error(res, err)
        }
    },
    // 更新商品
    updateGoods: async ({ body }, res) => {
        try {
            console.log('请求参数', body)
            response.success(res)
        } catch(err) {
            response.error(res, err)
        }
    }
}

module.exports = menuController
